/*
 * Copyright (c) 2015  3 7
 * ---10 :54:40
 * ---作者:吴培基
 * ---QQ:757671834
 */

package kali.wpj.kali.scan;

import android.app.Dialog;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.Style;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.marshalchen.common.commonUtils.urlUtils.HttpUtilsAsync;
import com.marshalchen.common.ui.ToastUtil;
import com.marshalchen.common.uimodule.slideactivity.IntentUtils;

import org.apache.http.Header;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.InjectView;
import kali.wpj.kali.MainActivity;
import kali.wpj.kali.ProfileFragment;
import kali.wpj.kali.R;
import kali.wpj.kali.common.settingActivity;
import kali.wpj.kali.globe.ServiceInfo;
import kali.wpj.kali.model.MyAdapter;
import kali.wpj.kali.model.Result;
import kali.wpj.kali.util.AnimationUtil;
import kali.wpj.kali.util.DialogBuilderTools;
import kali.wpj.kali.util.IPTools;
import kali.wpj.kali.util.JSONTools;
import kali.wpj.kali.util.SDCardUtils;
import kali.wpj.kali.util.SharedTools;
import kali.wpj.kali.view.SearchDevicesView;

public class NmapActivity extends ActionBarActivity {
    private View rootView;
    private Fragment detailsAssertFragment;
    private boolean showAssert = false;
    private String URLCENTER = ":8080/linux/nmap/";
    private String REPORT_URL = ":8080/linux/report/";
    private String IP;
    private Dialog mDialog;
    private DialogBuilderTools dailog;

    String result = "";
    @InjectView(R.id.list_data)
    ListView list_data;
    @InjectView(R.id.btn_nmap_scan)
    Button btn_nmap_scan;
    @InjectView(R.id.ed_nmap_scan)
    EditText ed_nmap_scan;
    @InjectView(R.id.btn_nmap_report)
    Button btn_nmap_report;
    private SearchDevicesView search_device_view;
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nmap);
        ButterKnife.inject(this);

        //蒙版
        rootView = findViewById(R.id.root);

        final Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                if (rootView.getWidth() > 0) {
                    detailsAssertFragment = new MyJobDetailsAssertFragment();
                    getFragmentManager().beginTransaction()
                            .add(R.id.root, detailsAssertFragment)
                            .commit();
                } else {
                    mHandler.postDelayed(this, 100);
                }
            }
        }, 500);
        ed_nmap_scan.setOnFocusChangeListener(onFocusChangeListener);
        btn_nmap_scan.setOnClickListener(btn_onClickerScanListener);

        btn_nmap_report.setOnClickListener(reportLoadingListener);
        search_device_view = new SearchDevicesView(NmapActivity.this);
        NmapActivity.this.addContentView(search_device_view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        search_device_view.setVisibility(View.GONE);
//        if (!IPTools.haveHostIP(NmapActivity.this)) {
//            SuperToast.create(this,  getString(R.string.setIP), SuperToast.Duration.LONG,
//                    Style.getStyle(Style.RED, SuperToast.Animations.SCALE)).show();
//
//            startActivity(new Intent(NmapActivity.this, settingActivity.class));
//            overridePendingTransition(R.anim.ac_transition_unzoom_in, R.anim.ac_transition_unzoom_out);
//        } else {

            IP = ServiceInfo.IP;
      //  }
        list_data.setLayoutAnimation(AnimationUtil.getListAnimTranslate());
        list_data.setOnItemClickListener(onItemClickListener);

    }

    /**
     * 下载报告
     */
    OnClickListener reportLoadingListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            HttpUtilsAsync.setTimeout(5000);
            HttpUtilsAsync.get("http://" + IP + REPORT_URL + "report", new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    Date date = new Date();
                    System.out.print("返回的流" + bytes);
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String now = dateFormat.format(date);
                    if (SDCardUtils.isSDCardEnable()) {
                        final String path = SDCardUtils.getSDCardPath();
                        Log.i("\nSDCardPath", path + "\n");
                        InputStream inputStream = null;
                        inputStream = new ByteArrayInputStream(bytes);
                        final String reportPath = path + "TimeFSafe";
                        SDCardUtils.writeToSDFromInput(reportPath, now + ".pdf", inputStream);
                        SuperToast.create(NmapActivity.this, now + getString(R.string.downSuccess)+ path + "TimeFSafe" , SuperToast.Duration.LONG,
                                Style.getStyle(Style.GREEN, SuperToast.Animations.FLYIN)).show();

                        /*对话框*/
                        final NiftyDialogBuilder dialogBuilder = NiftyDialogBuilder.getInstance(NmapActivity.this);
                        dialogBuilder
                                .withTitle(NmapActivity.this.getResources().getString(R.string.warning))                                  //.withTitle(null)  no title
                                .withTitleColor("#FFFFFF")                                  //def
                                .withDividerColor("#00000A")                              //def
                                .withMessage(getString(R.string.open))                     //.withMessage(null)  no Msg
                                .withMessageColor("#FFFFFFFF")                              //def  | withMessageColor(int resid)
                                .withDialogColor(getString(R.string.black))                               //def  | withDialogColor(int resid)
                                .withIcon(getResources().getDrawable(R.drawable.warn))
                                .withDuration(700)                                          //def
                                .withButton1Text(getString(R.string.open1))
                                .withButtonDrawable(R.color.white_translucent)
                                        //def gone
                                .withButton2Text(getString(R.string.cancle))                                  //def gone
                                .isCancelableOnTouchOutside(true)                           //def    | isCancelable(true)
                                .setCustomView(R.layout.custom_view, NmapActivity.this)         //.setCustomView(View or ResId,context)
                                .setButton1Click(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent();
                                        intent.setAction(Intent.ACTION_VIEW);
                                        Log.i("SDCArd", reportPath);
                                        intent.setDataAndType(Uri.fromFile(new File(reportPath)), "*/*");
                                        startActivity(intent);
                                    }
                                })
                                .setButton2Click(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialogBuilder.dismiss();
                                    }
                                })
                                .show();


                    } else {
                        SuperToast superToast = new SuperToast(NmapActivity.this);
                        superToast.setDuration(SuperToast.Duration.LONG);
                        superToast.setText( getString(R.string.sdnofound));
                        superToast.setIcon(SuperToast.Icon.Dark.INFO, SuperToast.IconPosition.LEFT);
                        superToast.show();

                        return;
                    }
                }

                @Override
                public void onCancel() {
                    super.onCancel();
                    SuperToast.create(NmapActivity.this,  getString(R.string.cancled), SuperToast.Duration.LONG,
                            Style.getStyle(Style.BLUE, SuperToast.Animations.FLYIN)).show();
        return ;

                }

                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                    SuperToast.create(NmapActivity.this,  getString(R.string.loadFail), SuperToast.Duration.LONG,
                            Style.getStyle(Style.RED, SuperToast.Animations.FLYIN)).show();

                }
            });
        }
    };


    /**
     * item点击事件
     */
    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.txt_port);
            String str = textView.getText().toString();
            String port = str.substring(0, str.lastIndexOf("/"));
            Intent intent = new Intent(NmapActivity.this, PortDetial_Activity.class);
            intent.putExtra("port", port);
            // startActivity(intent);
            IntentUtils.startPreviewActivity(NmapActivity.this, intent);
            overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        }
    };
//    AdapterView.OnItemClickListener onItemClickListener= (parent, view, position, id) -> {
//        TextView textView=(TextView)view.findViewById(R.id.txt_port);
//        String str=textView.getText().toString();
//        String port=str.substring(0, str.lastIndexOf("/"));
//        Toast.makeText(NmapActivity.this,"port"+port,Toast.LENGTH_LONG).show();
//    };
    /**
     * 文本款获取焦点
     */
    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText textView = (EditText) v;
            String hint;
            if (hasFocus) {
                hint = textView.getHint().toString();
                textView.setTag(hint);
                textView.setHint("");
            } else {
                hint = textView.getTag().toString();
                textView.setHint(hint);
            }
        }
    };


    /**
     * @see扫秒开始的事件监控
     */
    View.OnClickListener btn_onClickerScanListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String ip = ed_nmap_scan.getText().toString().trim();
            if (IPTools.isIPAddress(ip) || IPTools.isWeb(ip)) {
                getResult(IP, ip);
            } else {
                dailog = new DialogBuilderTools(NmapActivity.this);
                dailog.dialogShow(getString(R.string.IPOrWebError));
                return;
            }


        }
    };

    /**
     * 获取网络数据
     *
     * @param Ip 服务器ip
     * @param ip 待扫描ip
     */
    private void getResult(String Ip, String ip) {
        String tem = "http://" + Ip + URLCENTER + ip + "/";
        System.out.println("Nam" + tem);
        HttpUtilsAsync.get(tem, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                System.out.println(getString(R.string.ok) + bytes.toString());

                String str = null;
                try {
                    str = (new String(bytes, "UTF-8"));

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                System.out.println("-----------------------str-----------" + str);
                ArrayList<Result> list = (ArrayList<Result>) JSONTools.fromJsonTolist(str, new TypeToken<ArrayList<Result>>() {
                });
                System.out.println("-----------------------list-----------" + list);

                if (list == null) {
                    SuperToast.create(NmapActivity.this,getString(R.string.no), SuperToast.Duration.LONG,
                            Style.getStyle(Style.RED, SuperToast.Animations.FLYIN)).show();
                    return;
                }
                myAdapter = new MyAdapter(list, NmapActivity.this);
                list_data.setAdapter(myAdapter);
                btn_nmap_report.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFinish() {
                //   mDialog.dismiss();
                search_device_view.setSearching(false);
                search_device_view.setVisibility(View.GONE);

            }

            @Override
            public void onStart() {
                search_device_view.setWillNotDraw(false);
                search_device_view.setSearching(true);
                search_device_view.setVisibility(View.VISIBLE);

                //      showRoundProcessDialog(NmapActivity.this, R.layout.loading_process_dialog_anim);
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                SuperToast.create(NmapActivity.this ,getString(R.string.checkweb), SuperToast.Duration.LONG,
                        Style.getStyle(Style.BLUE, SuperToast.Animations.FADE)).show();
            }
        });


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scan_recored, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.scan_record_menu) {
            startActivity(new Intent(NmapActivity.this, ProfileFragment.class));
            overridePendingTransition(R.anim.ac_transition_flip_horizontal_in, R.anim.ac_transition_flip_horizontal_out);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(NmapActivity.this, MainActivity.class));

        NmapActivity.this.finish();
    }


    private void hideTheAssert() {
        getFragmentManager().beginTransaction()
                .remove(detailsAssertFragment)
                .commit();

        showAssert = false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (showAssert && keyCode == KeyEvent.KEYCODE_BACK) {
            hideTheAssert();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    class MyJobDetailsAssertFragment extends Fragment {

        public void MyJobDetailsAssertFragment() {

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.my_jobs_details_assert, null);
//			LogUnit.Log(TAG, "create assert "+rootView.getWidth()+"  "+rootView.getHeight());
            LayoutParams params = new LayoutParams(rootView.getWidth(), rootView.getHeight());
            view.setLayoutParams(params);
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    hideTheAssert();
                }
            });
//			view.setAlpha(60.0f);
            showAssert = true;
            return view;
        }
    }


}
